<?php
namespace Catalog\Service;

use Zend\Paginator\Adapter\DbSelect;

/**
 * 
 * @author Paolo Bertuzzo
 *
 */
class CategoryProductAdapter extends DbSelect
{
    /**
     * 
     */
    protected $productService;
    
    /**
     * 
     * @var string
     */
    protected $categoryAlias;

    /**
     *
     * @var string
     */
    protected $language;

    /**
     *
     * @var int
     */
    protected $storeId;
    
    /**
     * 
     * @var int
     */
    protected $count = null;
    
    /**
     * 
     * @param ProductService $productService
     * @param string $categoryAlias
     * @param string $language
     * @param int $storeId
     */
    public function __construct(ProductService $productService, $categoryAlias, $language, $storeId) 
    {
    	$this->productService = $productService;
    	$this->categoryAlias = $categoryAlias;
    	$this->language = $language;
    	$this->storeId = $storeId;
    }
    
    /**
     * (non-PHPdoc)
     * @see \Zend\Paginator\Adapter\DbSelect::getItems()
     */
    public function getItems($offset, $itemCountPerPage)
    {
        $localized_products = $this->productService->getProducts($this->categoryAlias, $this->language, $this->storeId, $offset, $itemCountPerPage);
        
        $products = array();
        
        for ($i = 0; $i < count($localized_products); $i += 5)
    	    array_push($products, array(
    	    	'product' => $localized_products[$i],
    	        'localized_name' => $localized_products[$i + 1],
    	        'alias' => $localized_products[$i + 2],
    	        'image' => $localized_products[$i + 3],
    	        'price' => $localized_products[$i + 4]
        ));
    	
    	return $products;
    }
    
    /**
     * (non-PHPdoc)
     * @see \Zend\Paginator\Adapter\DbSelect::count()
     */
    public function count()
    {
        if (!is_null($this->count))
            return $this->count;
        
    	$this->count = $this->productService->countProducts($this->categoryAlias, $this->language);
    	
        return $this->count;
    }
    
}

?>